package com.peking.donations.plugins.oauth2.client;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.oauth2.client.filter.OAuth2ClientContextFilter;
import org.springframework.security.oauth2.client.resource.UserRedirectRequiredException;
import org.springframework.security.web.DefaultRedirectStrategy;
import org.springframework.security.web.RedirectStrategy;
import org.springframework.web.util.UriComponentsBuilder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * 重写OAuth2ClientContextFilter 的redirectUser方法
 *
 * UriComponentsBuilder .fromHttpUrl() 改为 UriComponentsBuilder.fromUriString()
 * 提供url结尾是#的支持
 * 
 * @author Vigor Yuan
 */
public class CustomerOAuth2ClientContextFilter extends OAuth2ClientContextFilter {

    private RedirectStrategy redirectStrategy = new DefaultRedirectStrategy();

    Logger logger= LoggerFactory.getLogger(getClass());

    @Override
    protected void redirectUser(UserRedirectRequiredException e, HttpServletRequest request,
            HttpServletResponse response) throws IOException {

        String redirectUri = e.getRedirectUri();
        UriComponentsBuilder builder = UriComponentsBuilder.fromUriString(redirectUri);
        Map<String, String> requestParams = e.getRequestParams();
        for (Map.Entry<String, String> param : requestParams.entrySet()) {
            builder.queryParam(param.getKey(), param.getValue());
        }

        if (e.getStateKey() != null) {
            builder.queryParam("state", e.getStateKey());
        }
        logger.debug("oauth2 redirect url {}",builder.build().toUriString());
        this.redirectStrategy.sendRedirect(request, response, builder.build().toUriString());
    }
}
